#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gtk
from gtk import gdk
import gobject

import imageutil as iu

class EditWindow(gtk.DrawingArea):
    """The window to interact when editing layer_list.
    """
    # A checkerboard tile for the background
    background_tile = iu.pil_to_pixmap(iu.checkerboard())

    def __init__(self, layer_list, tool_box):
        """Makes a edit window for the given layerlist.
	"""
        super(EditWindow, self).__init__()
        self.add_events(gtk.gdk.BUTTON_PRESS_MASK|
                        gtk.gdk.BUTTON_RELEASE_MASK|
                        gtk.gdk.BUTTON_MOTION_MASK)
        self.layer_list = layer_list
        self.tool_box = tool_box
        self.action = None

    def do_expose_event(self, event):
        """Draw the layers.
        """
        self.draw_background(event)

        window = self.window
        gc = self.get_style().fg_gc[gtk.STATE_NORMAL]

        for layer in self.layer_list:
            layer.draw(event, gc)

    def do_button_press_event(self, event):
        if event.button == 1: # Left mouse button
            if self.layer_list.current:
                print "starting action"
                ActionType, params = self.tool_box.get_action()
                self.action = ActionType(self.layer_list.current, *params)
                self.action.update((event.x, event.y))
                self.queue_draw()

    def do_motion_notify_event(self, event):
        if self.action:
            print "updating action"
            self.action.update((event.x, event.y))
            self.queue_draw()

    def do_button_release_event(self, event):
        if self.action:
            print "action ends"
            self.action = None

    def draw_background(self, event):
        """Draw a background with the background tile.
        """
        window = event.window
        area = event.area

        gc = gdk.GC(window)
        gc.set_tile(self.background_tile)
        gc.fill = gdk.TILED

        window.draw_rectangle(gc, True,
                              area.x, area.y,
                              area.width, area.height)

    def update_size(self):
        """Updates the internal size of the widget.
        """
        width = max(layer.width for layer in self.layer_list)
        height = max(layer.height for layer in self.layer_list)
        self.set_size_request(width, height)

gobject.type_register(EditWindow)
